//
//  RequestParams.m
//  OCDemo
//
//  Created by zhumuzhi on 2021/3/18.
//

#import "RequestParams.h"
#import "twlt_uuid_util.h"

#define SOLE_KEY              @"ocd8Alc86oADjhfg14etAm"

@implementation RequestParams

#pragma mark - 单例方法
+ (instancetype)share{
    static dispatch_once_t t;
    static RequestParams *service = nil;
    dispatch_once(&t, ^{
        service = [[RequestParams alloc] init];
    });
    return service;
}


#pragma mark - 参数排序
- (NSMutableDictionary *)parameterSortWithDictionary:(NSDictionary *)dictionary{
    NSMutableDictionary *tempDic = [self getCommonParams:dictionary];
    NSArray *keys = [tempDic allKeys];
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSString *allStr = @"###";
    for (NSString *key in sortedArray) {
        id value = [tempDic objectForKey:key];
        NSString *valueString = [NSString stringWithFormat:@"%@",value];
        if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]]) {
            valueString = [value mj_JSONString];
        }
        if (ValidStr(valueString)) {
            NSString *keyValue = [NSString stringWithFormat:@"%@=%@",key,valueString];
            allStr = [NSString stringWithFormat:@"%@&%@",allStr,keyValue];
        }
    }
    allStr = [[NSString stringWithFormat:@"%@&secret=%@",allStr,SOLE_KEY] stringByReplacingOccurrencesOfString:@"###&" withString:@""];
    allStr = [allStr stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];//换行符转换处理
    allStr = [[allStr stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"] uppercaseString];//图片、附件路径在iOS中被转译成\/，需做处理
    NSString *sign = [allStr md5String];
    [tempDic setValue:sign forKey:@"sign"];
    return tempDic;
}

#pragma mark - 公参配置

- (NSMutableDictionary *)getCommonParams:(NSDictionary *)dictionary{
    NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithDictionary:dictionary];
    [tempDic setObject:[NSDate getCurrentTime] forKey:@"timestamp"];//当前日期时间戳
    [tempDic setObject:@"ios" forKey:@"device_platform"];//设备平台 android, ios,pc ,h5
    [tempDic setObject:kAppBuildVersion forKey:@"version_code"];//版本号
    [tempDic setObject:@"appstore" forKey:@"channel"];//下载渠道 xiaomi,appstore, huawei等等
    NSString *equipmentNo = twlt_uuid_create();//设备唯一标识
    if (ValidStr(equipmentNo)) {
        [tempDic setObject:equipmentNo forKey:@"device_id"];//终端的唯一标识
    }
//    [tempDic setObject:[NSString getNetworkType] forKey:@"network"];//网络状况 2G 3G 4G WIFI
    [tempDic setObject:@"苹果" forKey:@"device_brand"];//手机设备平台 小米 华为 苹果 三星
    [tempDic setObject:[[UIDevice currentDevice] systemVersion] forKey:@"os_version"];//操作系统版本
    return tempDic;
}

@end
